﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;

namespace Steve.Jobs
{
    public class AutomatedCategorizer
    {
        [Import]
        public ISearchQueryService Query { get; set; }
        [Import]
        public CategoryRepository Category { get; set; }
        [Import]
        public ContentRepository Content { get; set; }
        [Import]
        public ContentAdministrationRepository ContentUpdate { get; set; }
        [Import]
        public IConfiguration Config { get; set; }

        public void Run()
        {
            var cats = from c in Category.GetCategories()
                       where !string.IsNullOrWhiteSpace(c.AutomatedQuery)
                       select c;

            foreach (var cat in cats)
            {
                var matches = Query.Search(SearchType.LatestApproved, cat.AutomatedQuery);

                if (matches.ItemCount > 0 && matches.MaxScore >= Config.AutomatedCategorizerMinimumScore)
                {
                    foreach (var match in matches.Items.Where(i => i.RawScore >= Config.AutomatedCategorizerMinimumScore))
                    {
                        var content = Content.GetContentCategories(match.ContentId);

                        if (!content.Contains(cat.CategoryName))
                        {
                            ContentUpdate.SaveContentCategories(match.ContentId, content.Concat(new string[] { cat.CategoryName }));
                        }
                    }
                }
            }            
        }
    }
}
